<template>
  <div v-show="$route.name == 'store-loss-update'">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/store-loss-list' }">损耗列表</el-breadcrumb-item>
      <el-breadcrumb-item>编辑损耗记录</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <div style="margin-bottom: 20px;">编辑损耗</div>
      <!-- 搜索与添加区域 -->
      <el-form :model="saveForm"
      ref="saveFormRef"
      label-width="100px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="损耗时间" prop="apply_date">
              <el-date-picker type="date" placeholder="选择日期" v-model="saveForm.apply_date" readonly></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 商品表格 -->
        <el-row>
          <el-card>
             <!-- 搜索与添加区域 -->
             <el-row :gutter="20">
              <el-col :span="4">
                <el-button type="success" @click="showProductAddDialog()">新增</el-button>
              </el-col>
            </el-row>
            <!-- 商品列表区域 -->
            <el-table :data="saveForm.productList" border stripe height="300">
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column label="分类" prop="category_name"></el-table-column>
              <el-table-column label="商品" prop="name"></el-table-column>
              <el-table-column label="当前数量" prop="count_before"></el-table-column>
              <el-table-column label="剩余数量" prop="rest_count"></el-table-column>
              <el-table-column label="备注" prop="comment"></el-table-column>
              <el-table-column label="操作" width="120px">
                <template slot-scope="scope">
                  <!-- 修改按钮 -->
                  <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showProductEditDialog(scope.row, scope.$index)"></el-button>
                  </el-tooltip>
                  <!-- 删除按钮 -->
                  <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteProduct(scope.row)"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-row>
        <el-row style="margin-top: 20px;">
          <el-col>
            <el-button @click="back">返回</el-button>
            <el-button type="warning" @click="handleSubmit(0)">保存</el-button>
            <el-button type="primary" @click="handleSubmit(1)">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 保存商品对话框 -->
    <el-dialog :title="isProductAdd ? '新增商品' : '修改商品'" :visible.sync="saveProductDialogVisible" width="70%" @close="saveProductDialogClosed">
      <el-form :model="saveProductForm" :rules="saveProductFormRules" ref="saveProductFormRef" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="分类" prop="category_id">
              <el-select v-model="saveProductForm.category_id" popper-class="dropdownbox" style="width:200px" placeholder="请选择品类">
                <el-option v-for="item in categoryList" :label="item.category_name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.category_name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品" prop="store_id">
              <el-select v-model="saveProductForm.store_id" popper-class="dropdownbox" style="width:200px" placeholder="请选择商品">
                <el-option v-for="item in storeList" :label="item.name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="saveProductForm.unit" style="width:200px" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="当前数量" prop="count_before">
              <el-input v-model="saveProductForm.count_before" style="width:200px" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="剩余数量" prop="rest_count">
              <el-input-number controls-position="right" :precision="2" :step="1" :min="0" :max="saveProductForm.count_before ? parseFloat(saveProductForm.count_before) : 0" v-model="saveProductForm.rest_count" style="width:200px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="comment">
              <el-input v-model="saveProductForm.comment" style="width:200px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveProductDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveProduct">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      base: 0,
      loading: false,
      saveForm: {
        productList: [],
        apply_number: '',
        apply_date: '',
      },
      // 添加新的商品
      saveProductForm: {
        rest_count: 1,
        comment: '',
        store_id: '',
        category_id: '',
        category_name: '',
        name: '',
        unit: '',
        count_before: 0
      },
      // 添加表单的验证规则对象
      saveProductFormRules: {
        category_id: [
          { required: true, type: 'number', message: '请选择分类', trigger: 'change' }
        ],
        store_id: [
          { required: true, message: '请选择商品', trigger: 'change' }
        ],
        rest_count: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ]
      },
      // 仓库商品
      storeList: [],
      // 是否新增商品
      isProductAdd: true,
      saveProductDialogVisible: false,
      // 分类
      categoryList: [],
      // 是否需要重置goods
      isSet: 0
    }
  },
  watch: {
    'saveProductForm.store_id': {
      handler: function(val, oldval) {
        if (val) {
          let goodsDetail = {}
          goodsDetail = this.storeList.find((item) => {
            return item.id === val
          })
          if (goodsDetail) {
            this.saveProductForm.store_id = goodsDetail.id
            this.saveProductForm.name = goodsDetail.name
            this.saveProductForm.unit = goodsDetail.unit
            // this.saveProductForm.price_before = goodsDetail.price
            this.saveProductForm.count_before = goodsDetail.count
            this.saveProductForm.rest_count = goodsDetail.count
            // this.saveProductForm.total_amount_before = goodsDetail.total_amount
          }
        } else {
          this.saveProductForm.store_id = ''
          this.saveProductForm.name = ''
          this.saveProductForm.unit = ''
          // this.saveProductForm.price_before = 0
          this.saveProductForm.count_before = 0
          // this.saveProductForm.total_amount_before = 0
          this.saveProductForm.rest_count = 0
        }
      }
    },
    'saveProductForm.category_id': {
      handler: function(val, oldval) {
        if (val) {
          this.saveProductForm.category_name = this.categoryList.find((item) => {
            return item.id === val
          }).category_name
          this.getStoreList(val)
        } else {
          this.saveProductForm.category_name = ''
          this.storeList = []
          this.saveProductForm.store_id = ''
        }
      }
    }
  },
  mounted() {
    this.getUserInfo()
    this.getlossData()
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      const { data: result } = await this.$http.get('/user/' + localStorage.userid)
      if (result.status !== 200) return this.$message.error(result.msg)
      this.base = result.data.base *1
      this.getCategoryList()
    },
    getlossData() {
      if (this.$route.params.loss_id) {
        this.loss_id = this.$route.params.loss_id
        localStorage.setItem('lossId', this.$route.params.loss_id)
      } else {
        this.loss_id = localStorage.getItem('lossId')
      }
      if (this.loss_id) {
        this.getLossDetail(this.loss_id)
      }
    },
    async getLossDetail(loss_id) {
      const { data: result } = await this.$http.get('/store-loss/' + loss_id)
      if (result.status !== 200) {
        this.loading = false
        return this.$message.error(result.msg)
      }
      this.loading = false
      this.saveForm.productList = result.data.detail
      this.saveForm.apply_date = result.data.apply_date
      this.saveForm.apply_number = result.data.apply_number
    },
    // 获取分类
    async getCategoryList() {
      const { data: result } = await this.$http.get('/category', { params: {'base': this.base}} )
      if (result.status !== 200) return this.$message.error(result.msg)
      this.categoryList = result.data
    },
    // 显示修改商品对话框
    showProductEditDialog(contact, index) {
      this.isProductAdd = false
      this.saveProductForm = this.$_.cloneDeep(contact)
      this.modifyProductIndex = index
      this.saveProductDialogVisible = true
    },
    // 监听新增商品对话框的关闭事件
    saveProductDialogClosed() {
      this.isSet = 0
      if (this.isProductAdd) {
        this.$refs.saveProductFormRef.resetFields()
      }
    },
    // 删除商品
    async deleteProduct(product) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('删除该商品，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      this.saveForm.productList.splice(
        this.saveForm.productList.findIndex((existedProduct) => existedProduct === product),
        1
      )
      this.$message.success('删除商品成功！')
    },
    // 返回
    back() {
      this.$router.push({ 'name': 'store-loss-list' })
    },
    // 点击按钮，提交入库
    async handleSubmit(sure) {
      this.$refs.saveFormRef.validate(async (valid) => {
        if (!valid) return
        // 循环验证
        const handleData = []
        let check = []
        let flag = 1
        this.saveForm.productList.forEach(element => {
          if (flag === 1 && !element.store_id) {
            this.$message.error('提交失败，请商品必选')
            flag = 0
            return false
          }
          if (flag === 1 && (element.rest_count < 0 || element.rest_count.length === 0)) {
            this.$message.error('提交失败，余量有误')
            flag = 0
            return false
          }
          if (flag === 1 && check.indexOf(element.store_id) !== -1) {
            this.$message.error('数据重复')
            flag = 0
            return false
          }
          check.push(element.store_id)
          handleData.push({
            store_id: element.store_id,
            count: element.rest_count ? element.rest_count : 0,
            comment: element.comment ? element.comment : ''
          })
        })
        if (flag) {
          const { data: result } = await this.$http.put('/store-loss/' + this.loss_id , {
            data: handleData,
            sure: sure
          })
          if (result.status !== 200) {
            return this.$message.error(result.msg)
          }
          this.$message.success('保存成功')
          this.$router.push({ name: 'store-loss-list' })
        } else {
          return false
        }
      })
    },
    // 显示商品对话框
    showProductAddDialog() {
      this.isProductAdd = true
      this.saveProductForm = {
        rest_count: 1,
        comment: '',
        store_id: '',
        category_id: '',
        category_name: '',
        name: '',
        unit: '',
        // price_before: 0,
        count_before: 0
        // total_amount_before: 0
      }
      this.saveProductDialogVisible = true
      this.isSet = 1
    },
    async getStoreList(categoryId) {
      this.loading = true
      const params = {
        page: 1,
        pageSize: 1000000,
        base: this.base * 1,
        categoryId: categoryId,
        count: true
      }
      const { data: result } = await this.$http.get('/store/list', { params: params })
      if (result.status !== 200) {
        this.loading = false
        this.storeData = '暂无数据'
      }
      this.loading = false
      this.storeList = result.data
      if (this.isSet) {
        this.saveProductForm.store_id = ''          
      }
    },
    // 点击按钮，添加商品
    saveProduct() {
      this.$refs.saveProductFormRef.validate(async (valid) => {
        if (!valid) return
        var product = this.$_.cloneDeep(this.saveProductForm)
        // 修改
        if (!this.isProductAdd) {
          this.saveForm.productList.splice(this.modifyProductIndex, 1, product)
          this.$message.success('修改商品成功！')
        } else {
          // 新增
          this.saveForm.productList.push(product)
          this.$message.success('添加商品成功！')
        }
        // 隐藏添加商品的对话框
        this.isSet = 0
        this.saveProductDialogVisible = false
      })
    },
  }
}
</script>